<?php
namespace Application\Component;
use Doctrine\ORM\EntityManager;
use Application\Entity\Friend;
use DateTime;
use Application\Component\AbstractComponent;
/**
 * FriendServcie
 *
 */
class FriendComponent extends AbstractComponent
{
    protected  $entity="Application\\Entity\\Friend";

 
	function insert($friend)
	{
		$datetime = new DateTime("now");
		$friend->createdAt = $datetime;
		$friend->modifiedAt = $datetime;
		$this->em->persist($friend);
		$this->em->flush();
	}
	
	
	function update($friend)
	{
		$datetime = new DateTime("now");
		$friend->modifiedAt = $datetime;
		$this->em->persist($friend);
		$this->em->flush();
	}
	
	function get($id)
	{
		$friend = $this->em->find($this->entity, $id);
		return  $friend;
	}
	
	function getAll()
	{
		$friend = $this->em->getRepository($this->entity)->findAll();
		return  $friend;
	}
	
	function getMapFriend($userId)
	{
		$mapFriend = array();
		 
		$friends = $this->em->getRepository($this->entity)->getByUser($userId);
		foreach($friends[0] as $friend)
		{
			if($friend->userTo==$userId)
			{
				if(!array_key_exists($friend->userFrom,$mapFriend))
				{
					$mapFriend[$friend->userFrom] = $friend;
				}
			}else if($friend->userFrom==$userId){
				if(!array_key_exists($friend->userTo,$mapFriend))
				{
					$mapFriend[$friend->userTo] = $friend;
				}
			}
		}
		return  $mapFriend;
	}

    public function listByUser($userId, $offset=0, $limit = 0, $confirmed=-1, $toId = null)
    {
    	return $this->em->getRepository($this->entity)->listByUser($userId, $offset, $limit, $confirmed, $toId);
    }
	
	function getByUser($userId)
	{
		$friend = $this->em->getRepository($this->entity)->getByUser($userId);
		return  $friend;
	}
	
	function getByUserTo($userId)
	{
		$friend = $this->em->getRepository($this->entity)->getByUserTo($userId);
		return  $friend;
	}
	function getByUserFrom($userId)
	{
		$friend = $this->em->getRepository($this->entity)->getByUserFrom($userId);
		return  $friend;
	}
	
	
	function delete($id)
	{
		$friend = $this->em->find($this->entity, $id);
		$this->em->remove($friend);
		$this->em->flush();
	}
}
